/**
 * OKR Redux Toolkit Slice
 * 用于管理 OKR 树形结构的状态
 */

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import type {
  OKRState,
  OKRNode,
  CreateOKRNodeRequest,
  UpdateKeyResultRequest
} from '../types/okr';
import { mockOKRApi } from '@/api/mockOKRApi';


// 初始状态
const initialState: OKRState = {
  nodes: {},
  rootNodes: [],
  selectedNodeId: undefined,
  hoveredNodeId: undefined,
  collapsedNodes: [], // 折叠的节点ID数组
  loading: false,
  error: undefined,
  quarters: ['2024Q1', '2024Q2', '2024Q3', '2024Q4'],
  currentQuarter: '2024Q4'
};

// 异步 thunk actions

/**
 * 获取 OKR 树数据
 */
export const fetchOKRTree = createAsyncThunk(
  'okr/fetchTree',
  async (quarter: string) => {
    const response = await mockOKRApi.getOKRTree(quarter);
    return response;
  }
);

/**
 * 创建新的 OKR 节点
 */
export const createOKRNode = createAsyncThunk(
  'okr/createNode',
  async (nodeData: CreateOKRNodeRequest) => {
    const response = await mockOKRApi.createOKRNode(nodeData);
    return response;
  }
);

/**
 * 更新 OKR 节点信息
 */
export const updateOKRNode = createAsyncThunk(
  'okr/updateNode',
  async ({ nodeId, data }: { nodeId: string; data: Partial<OKRNode> }) => {
    const response = await mockOKRApi.updateOKRNode(nodeId, data);
    return response;
  }
);

/**
 * 删除 OKR 节点
 */
export const deleteOKRNode = createAsyncThunk(
  'okr/deleteNode',
  async (nodeId: string) => {
    await mockOKRApi.deleteOKRNode(nodeId);
    return nodeId;
  }
);

/**
 * 更新关键结果进度
 */
export const updateKeyResult = createAsyncThunk(
  'okr/updateKeyResult',
  async (updateData: UpdateKeyResultRequest) => {
    const response = await mockOKRApi.updateKeyResult(updateData);
    return response;
  }
);

// OKR Slice
const okrSlice = createSlice({
  name: 'okr',
  initialState,
  reducers: {
    /**
     * 设置选中的节点
     */
    setSelectedNode: (state, action: PayloadAction<string | undefined>) => {
      state.selectedNodeId = action.payload;
    },

    /**
     * 设置悬浮的节点
     */
    setHoveredNode: (state, action: PayloadAction<string | undefined>) => {
      state.hoveredNodeId = action.payload;
    },

    /**
     * 切换节点的折叠状态
     */
    toggleNodeCollapse: (state, action: PayloadAction<string>) => {
      const nodeId = action.payload;
      const index = state.collapsedNodes.indexOf(nodeId);
      if (index >= 0) {
        state.collapsedNodes.splice(index, 1);
      } else {
        state.collapsedNodes.push(nodeId);
      }
    },

    /**
     * 展开所有节点
     */
    expandAllNodes: (state) => {
      state.collapsedNodes = [];
    },

    /**
     * 折叠所有节点（除根节点外）
     */
    collapseAllNodes: (state) => {
      // 折叠所有非叶子节点
      const collapsedIds: string[] = [];
      Object.values(state.nodes).forEach(node => {
        if (node.children.length > 0 && node.level > 0) {
          collapsedIds.push(node.id);
        }
      });
      state.collapsedNodes = collapsedIds;
    },

    /**
     * 设置初始折叠状态（默认折叠深层节点）
     */
    setInitialCollapseState: (state) => {
      const collapsedIds: string[] = [];
      // 默认折叠 level >= 2 的节点
      Object.values(state.nodes).forEach(node => {
        if (node.children.length > 0 && node.level >= 2) {
          collapsedIds.push(node.id);
        }
      });
      state.collapsedNodes = collapsedIds;
    },

    /**
     * 切换当前季度
     */
    setCurrentQuarter: (state, action: PayloadAction<string>) => {
      state.currentQuarter = action.payload;
    },

    /**
     * 清除错误信息
     */
    clearError: (state) => {
      state.error = undefined;
    },

    /**
     * 重置状态
     */
    resetOKRState: (state) => {
      state.nodes = {};
      state.rootNodes = [];
      state.selectedNodeId = undefined;
      state.hoveredNodeId = undefined;
      state.error = undefined;
    }
  },
  extraReducers: (builder) => {
    // 获取 OKR 树数据
    builder
      .addCase(fetchOKRTree.pending, (state) => {
        state.loading = true;
        state.error = undefined;
      })
      .addCase(fetchOKRTree.fulfilled, (state, action) => {
        state.loading = false;
        const { nodes, rootNodes } = action.payload.data;
        state.nodes = nodes;
        state.rootNodes = rootNodes;
        // 设置初始折叠状态（默认折叠小组及以下层级）
        const collapsedIds: string[] = [];
        Object.values(nodes).forEach(node => {
          if (node.children.length > 0 && node.level >= 2) {
            collapsedIds.push(node.id);
          }
        });
        state.collapsedNodes = collapsedIds;
      })
      .addCase(fetchOKRTree.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取 OKR 数据失败';
      });

    // 创建 OKR 节点
    builder
      .addCase(createOKRNode.pending, (state) => {
        state.loading = true;
        state.error = undefined;
      })
      .addCase(createOKRNode.fulfilled, (state, action) => {
        state.loading = false;
        const newNode = action.payload.data;
        state.nodes[newNode.id] = newNode;

        // 如果是根节点，添加到 rootNodes
        if (!newNode.parentId) {
          state.rootNodes.push(newNode.id);
        } else {
          // 否则添加到父节点的 children 中
          const parentNode = state.nodes[newNode.parentId];
          if (parentNode) {
            parentNode.children.push(newNode.id);
          }
        }
      })
      .addCase(createOKRNode.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '创建 OKR 节点失败';
      });

    // 更新 OKR 节点
    builder
      .addCase(updateOKRNode.pending, (state) => {
        state.loading = true;
        state.error = undefined;
      })
      .addCase(updateOKRNode.fulfilled, (state, action) => {
        state.loading = false;
        const updatedNode = action.payload.data;
        state.nodes[updatedNode.id] = updatedNode;
      })
      .addCase(updateOKRNode.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '更新 OKR 节点失败';
      });

    // 删除 OKR 节点
    builder
      .addCase(deleteOKRNode.pending, (state) => {
        state.loading = true;
        state.error = undefined;
      })
      .addCase(deleteOKRNode.fulfilled, (state, action) => {
        state.loading = false;
        const nodeId = action.payload;
        const node = state.nodes[nodeId];

        if (node) {
          // 从父节点的 children 中移除
          if (node.parentId) {
            const parentNode = state.nodes[node.parentId];
            if (parentNode) {
              parentNode.children = parentNode.children.filter(id => id !== nodeId);
            }
          } else {
            // 从根节点列表中移除
            state.rootNodes = state.rootNodes.filter(id => id !== nodeId);
          }

          // 递归删除所有子节点
          const deleteNodeRecursively = (id: string) => {
            const nodeToDelete = state.nodes[id];
            if (nodeToDelete) {
              nodeToDelete.children.forEach(childId => {
                deleteNodeRecursively(childId);
              });
              delete state.nodes[id];
            }
          };

          deleteNodeRecursively(nodeId);
        }

        // 如果删除的是当前选中的节点，清除选中状态
        if (state.selectedNodeId === nodeId) {
          state.selectedNodeId = undefined;
        }
      })
      .addCase(deleteOKRNode.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '删除 OKR 节点失败';
      });

    // 更新关键结果
    builder
      .addCase(updateKeyResult.pending, (state) => {
        state.error = undefined;
      })
      .addCase(updateKeyResult.fulfilled, (state, action) => {
        const { nodeId, keyResult } = action.payload.data;
        const node = state.nodes[nodeId];
        if (node) {
          const keyResultIndex = node.keyResults.findIndex(kr => kr.id === keyResult.id);
          if (keyResultIndex !== -1) {
            node.keyResults[keyResultIndex] = keyResult;

            // 重新计算节点进度
            const totalProgress = node.keyResults.reduce((sum, kr) => sum + kr.progress, 0);
            node.progress = Math.round(totalProgress / node.keyResults.length);
          }
        }
      })
      .addCase(updateKeyResult.rejected, (state, action) => {
        state.error = action.error.message || '更新关键结果失败';
      });
  }
});

// 导出 actions
export const {
  setSelectedNode,
  setHoveredNode,
  toggleNodeCollapse,
  expandAllNodes,
  collapseAllNodes,
  setInitialCollapseState,
  setCurrentQuarter,
  clearError,
  resetOKRState
} = okrSlice.actions;

// 导出 selectors
export const selectOKRNodes = (state: { okr: OKRState }) => state.okr.nodes;
export const selectRootNodes = (state: { okr: OKRState }) => state.okr.rootNodes;
export const selectSelectedNode = (state: { okr: OKRState }) =>
  state.okr.selectedNodeId ? state.okr.nodes[state.okr.selectedNodeId] : undefined;
export const selectHoveredNode = (state: { okr: OKRState }) =>
  state.okr.hoveredNodeId ? state.okr.nodes[state.okr.hoveredNodeId] : undefined;
export const selectOKRLoading = (state: { okr: OKRState }) => state.okr.loading;
export const selectOKRError = (state: { okr: OKRState }) => state.okr.error;
export const selectCurrentQuarter = (state: { okr: OKRState }) => state.okr.currentQuarter;
export const selectQuarters = (state: { okr: OKRState }) => state.okr.quarters;

// 导出 reducer
export default okrSlice.reducer;
